import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui';
import Login from '@/views/login/Login.vue'
import NotFound from '@/views/NotFound.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '',
        redirect: '/login'
    },
    { path:'*' ,component: NotFound},
    {
        path: '/login',
        name: 'Login',
        component: Login
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
//重置路由方法
export const resRouter = ()=>{
    new VueRouter()
}

export const setTrendsRouter = () => {
    let menus = sessionStorage.getItem('userInfo') ?JSON.parse(sessionStorage.getItem('userInfo')).menus:[]
    let tem = {path: '/home',name: 'home',component: (resolve) => require(['@/views/home/Home.vue'], resolve),children: []}

    menus.forEach(item =>{
        if(item.children.length == 0){
            tem.children.push({
                path: item.path,
                name: item.path,
                component: () => import(`@/views/${item.path}/${item.path.slice(0,1).toUpperCase() + item.path.slice(1)}.vue`)
            })
        }else{
            item.children.forEach(v =>{
                tem.children.push({
                    path: v.path,
                    name: v.path,
                    component: () => import(`@/views/${v.path}/${v.path.slice(0,1).toUpperCase() + v.path.slice(1)}.vue`)
                })
            })
        }
    })

    //当前路由对象数组
    let currentRouters = router.getRoutes()

    let isExistRouter = currentRouters.findIndex(item => item.name == "home")
    // console.log(currentRouters)
    //判断是否已注册，防止重复注册
    if(isExistRouter == -1 && menus.length != 0){
        router.addRoute(tem)
    }
    router.addRoute(tem)
}
setTrendsRouter()
//路由白名单
let whiteList = ["/login"]
router.beforeEach((to, from, next) => {
    // 判断用户是否已登录
    let token = window.sessionStorage.getItem("token") ? window.sessionStorage.getItem("token"): ""
    let isPass = whiteList.findIndex(item=>to.fullPath == item)
    //未找到路由情况下
    // if(to.matched.length != 0 ){
    //     let menus = sessionStorage.getItem('userInfo') ?JSON.parse(sessionStorage.getItem('userInfo')).menus:[]
    //     if(!menus){
    //         next({ path: '/404' })
    //     }
    // }
    if(isPass == -1 && token == ""){
        Message.error('请登录!!!')
        // 如果用户未登录，则跳转到登录页面
        next({ path: '/login' })
    }else {
        next();
    }
})
export default router
